package com.ccp.dev.workflow.controller;

import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.annotion.ActionExecOrder;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.TimeUtil;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.workflow.model.BpmNodeSet;
import com.ccp.dev.workflow.model.BpmUserCondition;
import com.ccp.dev.workflow.service.BpmNodeSetService;
import com.ccp.dev.workflow.service.BpmUserConditionService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.text.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * ClassDescribe:用户条件配置 控制器类
 * @author :jiayueqiao
 * Date: 2019-05-24
 * Since:1
 */
@Controller
@RequestMapping(UrlConstants.PROJECT_ROOT +UrlConstants.PROJECT_MODULE_WORKFLOW+"/bpmUserCondition")
@Action(ownermodel = SysAuditModelType.PROCESS_MANAGEMENT)
public class BpmUserConditionController extends SysBaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(BpmUserConditionController.class);

    @Resource
    private BpmUserConditionService bpmUserConditionService;
    @Resource
    private BpmNodeSetService bpmNodeSetService;


    /**
     * 快捷设置人员保存
     * @param request http请求
     */
    @RequestMapping("/saveQuickly")
    @Action(description = "快捷设置人员保存",detail = "<#if suceess>快捷设置人员保存成功</#if>")
    @ResponseBody
    public ResultData saveQuickly(HttpServletRequest request){
        try{
            String procDefId = RequestUtil.getString(request, "procDefId");
            String userSetting = request.getParameter("userSetting");
            userSetting = StringEscapeUtils.unescapeHtml4(userSetting);
            String parentProcDefId = request.getParameter("parentProcDefId");
            JSONArray jarray = JSONArray.fromObject(userSetting);
            for(Object obj : jarray){
                JSONObject jobject = JSONObject.fromObject(obj);
                String nodeId = jobject.getString("nodeId");
                String setId = jobject.getString("setId");
                Long currentSn = TimeUtil.getCurrentTimeMillis();
                BpmUserCondition bpmUserCondition = new BpmUserCondition();
                bpmUserCondition.setSetId(setId);
                bpmUserCondition.setNodeId(nodeId);
                bpmUserCondition.setProcDefId(procDefId);
                bpmUserCondition.setSn(currentSn);
                bpmUserCondition.setFormIdentity("");
                bpmUserCondition.setParentProcDefId(parentProcDefId);
                String conditionShow=jobject.getString("conditionShow");
                bpmUserCondition.setConditionShow(conditionShow);
                String users = jobject.getString("users");
                bpmUserConditionService.saveConditionAndUser(bpmUserCondition, users);
            }
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("operation.success");

        }catch (Exception e) {
            LOGGER.error(e.getMessage());
            return getResultDataError("operation.failure");
        }

    }

    /**
     * 删除用户条件配置
     * @param request request
     */
    @RequestMapping("/del")
    @Action(description = "删除用户条件配置",execOrder = ActionExecOrder.BEFORE,detail = "用户条件配置删除<#if success>成功<#else>失败</#if>")
    @ResponseBody
    public ResultData del(HttpServletRequest request){
        try {
            String conditionIds = RequestUtil.getString(request,"conditionIds","");
            bpmUserConditionService.delByConditionIds(conditionIds);
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("delete.success");
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage());
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("delete.error");
        }
    }

    /**
     * 保存批次号
     * @param request
     * @return
     */
    @RequestMapping("/updateGroup")
    @Action(description = "保存批次号",detail = "<#if success>人员设置批次号保存成功</#if>")
    @ResponseBody
    public ResultData updateGroup(HttpServletRequest request){

        String ids = RequestUtil.getString(request,"conditionIds");
        String groupNos = RequestUtil.getString(request,"groupNos");
        String[] aryConditionId = ids.split(",");
        String[] aryGroupNo = groupNos.split(",");
        try{
            for (int i = 0; i < aryConditionId.length; i++) {
                BpmUserCondition bpmUserCondition = bpmUserConditionService.getOneById(aryConditionId[i]);
                bpmUserCondition.setGroupNo( Integer.parseInt(aryGroupNo[i]) );
                bpmUserConditionService.update(bpmUserCondition);
            }
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("save.success");
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            return getResultDataError("save.failure");
        }
    }

    /**
     * 添加或更新用户条件配置
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @Action(description = "添加或更新用户条件配置",detail = "<#if save>用户条件配置保存成功</#if>")
    @ResponseBody
    public ResultData save(HttpServletRequest request) throws Exception {
        String conditionId = RequestUtil.getString(request, "conditionId");
        String procDefId = RequestUtil.getString(request, "procDefId");
        String nodeId = RequestUtil.getString(request, "nodeId");
        String condition = RequestUtil.getString(request, "condition");
        condition = StringEscapeUtils.unescapeHtml4(condition);
        String users = request.getParameter("users");
        users = StringEscapeUtils.unescapeHtml4(users);
        if (StringUtil.isEmpty(users)) {
            users = "";
        }
        // 在列表中的展示内容
        String conditionShow = request.getParameter("conditionShow");
        if (StringUtil.isEmpty(conditionShow)) {
            conditionShow = "";
        }
        //人员规则类型，0为执行人员，1为抄送人员
        Integer conditionType = RequestUtil.getInt(request, "conditionType", 0);
        Long sn = RequestUtil.getLong(request, "sn");
        String formIdentity = RequestUtil.getString(request, "formIdentity");
        String parentProcDefId = RequestUtil.getString(request, "parentProcDefId", "");

        try {
            BpmUserCondition bpmUserCondition = null;
            if (StringUtil.isEmpty(conditionId)) {
                bpmUserCondition = new BpmUserCondition();
            } else {
                bpmUserCondition = bpmUserConditionService.getOneById(conditionId);
            }

            bpmUserCondition.setNodeId(nodeId);
            bpmUserCondition.setProcDefId(procDefId);
            bpmUserCondition.setSn(sn);
            bpmUserCondition.setCondition(condition);
            bpmUserCondition.setFormIdentity(formIdentity);
            // 如果节点不为空,获取setId设置到用户条件当中。
            if (StringUtil.isNotEmpty(nodeId)) {
                BpmNodeSet bpmNodeSet = null;
                if (StringUtil.isEmpty(parentProcDefId)) {
                    bpmNodeSet = bpmNodeSetService.getByProcDefIdNodeIdOrParentProcDefId(nodeId,procDefId ,"");
                } else {
                    bpmNodeSet = bpmNodeSetService.getByProcDefIdNodeIdOrParentProcDefId(nodeId,procDefId,parentProcDefId);
                }
                if (BeanUtils.isNotEmpty(bpmNodeSet)) {
                    bpmUserCondition.setSetId(bpmNodeSet.getSetId());
                }
            }

            bpmUserCondition.setConditionShow(conditionShow);
            bpmUserCondition.setConditionType(conditionType);
            bpmUserCondition.setParentProcDefId(parentProcDefId);
            bpmUserConditionService.saveConditionAndUser(bpmUserCondition, users);
            SysAuditThreadLocalHolder.putParamerter("save",true);
            return getResultDataSuccess("operation.success");
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            return getResultDataError("operation.failure");
        }
    }

    /**
     * 保存排序
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("saveSn")
    @Action(description = "更新抄送人员设置的条件排序",detail = "<#if success>人员设置条件排序保存成功</#if>")
    @ResponseBody
    public ResultData saveSn(HttpServletRequest request){
        String[] conditionIds = RequestUtil.getStringAryByStr(request, "conditionIds");
        try {
            for (int i = 1; i <= conditionIds.length; i++) {
                bpmUserConditionService.updateSn(conditionIds[i], i);
            }
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("save.success");
        }catch (Exception e){
            LOGGER.error(e.getMessage());
            return getResultDataError("save.failure",1,e.getMessage());
        }
    }
}
